package com.sali.msg;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class ChunkedServer {
    public static void main(String[] args) throws IOException {
        int port = 8080;
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);

        server.createContext("/data", new DataHandler());
        server.setExecutor(null);
        server.start();
    }

    static class DataHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            // 设置响应头，指定使用chunked编码
            exchange.getResponseHeaders().set("Transfer-Encoding", "chunked");
            exchange.sendResponseHeaders(200, 0);

            OutputStream os = exchange.getResponseBody();

            // 模拟发送一些数据
            for (int i = 1; i <= 10; i++) {
                String chunk = "Chunk " + i + "\r\n";
                os.write(chunk.getBytes());
                os.flush();
                try {
                    Thread.sleep(1000); // 每隔1秒发送一个chunk
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            os.close();
        }
    }
}
